@extends("ogreencard.layout.layout")
@section("h1","订单管理")
@section("h2","订单导入")
@section("content")

    <div class="layui-fluid">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-body">
                        <form class="layui-form layui-col-space5" action="?XDEBUG_SESSION_START=PHPSTORM"  method="post" enctype="multipart/form-data">
                            <input type="hidden" name="_token" id="token" value="{{csrf_token()}}">
                            <div class="layui-inline layui-show-xs-block">
                                <input type="file" required name="excel"  class="layui-input" accept=".xls,.xlsx">
                            </div>

                            <div class="layui-inline layui-show-xs-block">
                                <button class="layui-btn layui-btn-normal">
                                    <i class="layui-icon">&#xe681;</i>上传EXCEL
                                </button>
                            </div>

                            <div class="layui-inline layui-show-xs-block">
                                <a class="layui-btn " href="/ogreencard/file/order-import.xlsx">
                                    <i class="layui-icon">&#xe601;</i>下载模板
                                </a>
                            </div>
                        </form>
                    </div>

                    <div class="layui-card-body">

                        <div class="layui-table-box">
                            <style>
                                .order-table th,.order-table td{
                                    padding:10px 0 !important;
                                    text-align: center;
                                }
                            </style>
                            <table class="layui-table layui-form order-table"  lay-filter="">
                                <thead>
                                <tr>
                                    <th>#</th>
                                    <th>客户姓名</th>
                                    <th>联系方式</th>
                                    <th>支行</th>
                                    <th>理财经理</th>
                                    <th>销售</th>
                                    <th>兑换日期</th>
                                    <th>刷分类型</th>
                                    <th>订单类型</th>
                                    <th>收件人</th>
                                    <th>收件电话</th>
                                    <th>收件/拍摄地址</th>
                                    <th>配送/拍摄日期</th>
                                    <th>快递公司</th>
                                    <th>快递单号</th>
                                    <th>订单备注</th>
                                    <th>验证信息</th>
                                    <th>卡号、流水号</th>
                                    <th>兑换产品</th>
                                    <th>总积分</th>
                                    <th>已选积分</th>
                                    <th>
                                        <spsn class="layui-btn" onclick="show_goods(-1);">选择</spsn>
                                        <spsn class="layui-btn" onclick="xadmin.open('添加类型','cardTypeEdit?id=0&from=order',700,500)">新增</spsn>
                                    </th>
                                </tr>
                                </thead>
                                <tbody>
                                @foreach($orders as $key=>$o)
                                <tr id="order-{{$key}}">
                                    <td>{{$key+1}}</td>
                                    <td>{{$o["name"]}}</td>
                                    <td>{{$o["mobile"]}}</td>
                                    <td>{{$o["bank"]}}</td>
                                    <td>{{$o["bank_manager"]}}</td>
                                    <td>{{$o['manager']}}</td>
                                    <td>{{$o["date"]}}</td>
                                    <td>{{$o['type']}}</td>
                                    <td>{{$o["card_type"]}}</td>
                                    <td>{{$o['express_user']}}</td>
                                    <td>{{$o['express_mobile']}}</td>
                                    <td>{{$o['express_address']}}</td>
                                    <td>{{$o['express_date']}}</td>
                                    <td>{{$o['express_company']}}</td>
                                    <td>{{$o['express_code']}}</td>
                                    <td>{{$o["note"]}}</td>
                                    <td class="x-red">{!! $o['msg'] !!}</td>
                                    <td>{!! str_replace("\n","<br/>",$o["cards"])!!}</td>
                                    <td class="selectedGoods"></td>
                                    <td>{{$o["price"]}}</td>
                                    <td class="selectedPrice x-red"></td>
                                    <td>
                                        @if(!$hasError)
                                        <spsn class="layui-btn" onclick="show_goods({{$key}});">选择</spsn>
                                        @endif
                                    </td>
                                </tr>
                                @endforeach
                                </tbody>
                            </table>

                            @if(!$hasError && count($orders) > 0)
                                <div style="text-align: center;">
                                    <br><button class="layui-btn layui-btn-danger" onclick="submitOrder()">提交</button><br>
                                </div>
                            @endif
                        </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        .goods-model{
            display:none;
            position:fixed;
            top:0;
            left:0;
            background:rgba(0,0,0,.5);
            width:100vw;
            height:100vh;
            text-align:center;
            z-index:100;
        }
        .goods-box{
            width:700px;
            height:100vh;
            background:#fff;
            display: flex;
            flex-direction: column;
            margin:auto;
        }

        /*操作按钮*/
        .point{
            border-radius: 100%;
            border: 1px solid #999;
            padding: 2px;
            margin: 2px;
            cursor: pointer;
        }

        .goods-list{
            overflow-y: scroll;
            margin:auto;
            flex: 1;
        }

        .select-goods-sure-btn{
            left:0;
            width:100%;
            text-align: center;
            border: 10px solid #999;
            box-sizing: border-box;
        }


    </style>
    <div class="goods-model">
        <div class="goods-box">

            <div class="select-goods-sure-btn">
                <table class="layui-table">
                    <tr>
                        <td><input id="searchText" class="layui-input" placeholder="搜索" onkeyup="search_goods(this)"></td>
                        <td class="priceNotice" style="font-size:20px;font-weight: bold;color:red;"></td>
                        <td class="x-red" id="count">0</td>
                        <td><span class="layui-btn" onclick="hidden_goods()">确定</span></td>
                    </tr>
                </table>
            </div>

            <div class="goods-list">
                <table class="layui-table layui-form" style="text-align: left;" lay-fileter="goods" id="goods-table">
                    <thead>
                    <tr>
                        <th width="30">
                        </th>
                        <th style="width:100px;">数量</th>
                        <th width="40">合计</th>
                        <th>产品名称</th>
                        <th>单品备注</th>
                        <th width="50">产品积分</th>
                    </tr>
                    </thead>
                    <tbody>
                    @foreach($goods as $g)
                        <tr id="g-{{$g->pack_id}}" data-id="{{$g->pack_id}}" data-search="{{$g->pack_price}}{{$g->pack_name}}" data-name="{{$g->pack_name}}" class="goods">
                            <td onclick="count_price()">
                                <input type="checkbox" name="id" value="{{$g->pack_id}}"   lay-skin="primary" >
                            </td>
                            <td onselectstart="return false;">
                                <i class="icon iconfont point" data-type="reduce" onclick="addNum(this)" ondblclick="return false;">&#xe6fe;</i>
                                <input type="text" class="layui-input num" style="width:30px;display: inline-block;" value="1">
                                <i class="icon iconfont point" data-type="add" onclick="addNum(this)" ondblclick="return false;">&#xe6b9;</i>
                            </td>
                            <td class="total"></td>
                            <td>{{$g->pack_name}}</td>
                            <td><input type="text" class="note layui-input"></td>
                            <td class="price">{{$g->pack_price}}</td>
                        </tr>
                    @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        var orders = {!! json_encode($orders) !!};

        var form ;
        var layer ;
        layui.use(['laydate','jquery','layer','table','form'], function()
        {
            var laydate = layui.laydate;
            table = layui.table;
            form = layui.form;
            layer = layui.layer;
            //执行一个laydate实例
            laydate.render({
                elem: '#start' //指定元素
            });

        });

        var minKey = 0;//选择第一个订单
        var maxKey = 0;//选择的最后一个订单
        function show_goods(key) {
            if(orders.length == 0) {
                return layer.msg('请先导入订单',{icon:7,time:2000});
            }
            if(key >= 0) {
                minKey = key;
                maxKey = key+1;
            } else {
                minKey = 0;
                maxKey = orders.length;
            }

            $(".goods-model").show();

            if(key < 0){
                var goods = [];
            }else{
                var goods = orders[key]['goods'];
            }

            //将已经选择的商品展示
            var gList = $(".goods");
            gList.find(".total").text(0);//单产品合计
            gList.find(".num").val(1);//产品数量
            gList.find('.note').val("");//产品备注
            $(".goods").find("input[type=checkbox]").prop("checked",false);//取消选中

            for(var g of goods)
            {
                var tr = $("#g-"+g.id);
                tr.find("input[type=checkbox]").prop("checked",true);
                tr.find(".num").val(g.num);
                tr.find(".note").val(g.note);
            }
            form.render('checkbox');
            count_price();
        }

        /*隐藏产品*/
        function hidden_goods() {
            $(".goods-model").hide();
            count_price();
            show_order_goods();
        }

        function show_order_goods(){
            for (let i=minKey;i<maxKey;i++){
                var goods = orders[i].goods;
                var text = "";
                if(goods.length>0){
                    for(var g of goods){
                        text += g.name + "X"+g.num+"<br>";
                    }
                }
                $("#order-"+i).find(".selectedGoods").html(text);
                $("#order-"+i).find(".selectedPrice").text(orders[i].totalPrice)
            }
        }

        function set_cache(){
            localStorage.setItem('orders',JSON.stringify(orders));
        }

        function get_cache(){
            let cacheOrders = localStorage.getItem('orders');
            let length = orders.length;
            if(cacheOrders){
                cacheOrders = JSON.parse(cacheOrders);
                for(let i=0;i<length;i++){
                    orders[i].goods = cacheOrders[i].goods;
                    orders[i].totalPrice = cacheOrders[i].totalPrice;
                }
                localStorage.removeItem('orders');
            }
            minKey = 0;
            maxKey = length;
            console.log(minKey,',',maxKey);
            show_order_goods();
        }
        setTimeout(get_cache,2000);

        var searchGoodsList = null;
        function search_goods(obj){

            let text = $(obj).val();
            console.log(text);
            if(!searchGoodsList) {
                searchGoodsList = $('#goods-table .goods');
            }

            //关闭显示
            if(text == ''){
                $('#goods-table .goods').show();
                return;
            }

            let length = searchGoodsList.length;
            for(let k=0;k<length;k++) {
                let ele = searchGoodsList.eq(k);
                if(ele.data('search').indexOf(text) >=0  ){
                        ele.show();
                }else{
                        ele.hide();
                }
            }
        }

        /*改变产品数量*/
        function addNum(ele){

            ele = $(ele);
            var tr = ele.parents("tr");
            var num = tr.find('.num').eq(0).val();
            var type = ele.data('type');

            if(type == 'reduce'){
                num -= 1;
                if(num<0) return;
            }else{
                num = (num*1) + 1;
            }
            tr.find('.num').eq(0).val(num);

            count_price();
        }
        /*统计价格*/
        function count_price() {
            var total = 0;
            //取消所有已经选中的产品


            for(let i=minKey;i<maxKey;i++) {
                orders[i].goods = [];
            }

            $(".goods").each(function()
            {
                var _this = $(this);
                var isChecked = _this.find("input[type=checkbox]").eq(0).prop("checked");
                var price = _this.find('.price').text();
                var num = _this.find(".num").eq(0).val();
                var note = _this.find(".note").val();
                var single = num*price;

                if(isChecked){

                    for(let i=minKey;i<maxKey;i++){
                        orders[i].goods.push({
                            id:_this.data("id"),
                            name:_this.data("name"),
                            num:num,
                            note:note
                        });
                    }
                    total += single;
                }
                _this.find('.total').text(single);
            });

            var maxPrice = orders[minKey].price;    //这里如果是批量选择，将以第一个的价格为计算标准
            if(total > maxPrice){
                var msg = "多"+(total-maxPrice)+"分";
            }else{
                var msg = "差"+(maxPrice-total)+"分";
            }

            $(".priceNotice").text(msg);
            $("#count").text(total);
            for(let i=minKey;i<maxKey;i++){
                orders[i].totalPrice = total;
            }
        }
        var submitting = false;
        /*提价订单*/
        function submitOrder(){
            //检查积分总数是否超过最大可选树木
            for(var i in orders){
                var order = orders[i];
                var n = i*1+1;

                if(typeof order.totalPrice == "undefined" || order.totalPrice < 1){
                    layer.msg("第"+n+"条订单未选择产品",{icon:7,time:2000});
                    return;
                }

                if(order.totalPrice != order.price){
                    layer.msg("第"+n+"条订单商品积分和总积分不一致",{icon:7});
                    return;
                }
            }
            if(submitting) return;
            submitting = true;
            $.post({
                url:"./orderImport",
                data:{_token:$("#token").val(),'orders':orders},
                success:function(res)
                {
                   submitting = false;
                   if(res.code==200){
                       layer.msg("添加成功",{icon:6},function(){
                            setTimeout(()=>{
                                location.href = location.href;
                            },2000);
                       });
                   }else{
                       layer.msg(res.msg,{icon:7,time:2000},function(){

                       });
                   }
                },
                fail:function(){
                    submitting = false;
                }
           })
        }
    </script>
@endsection
